<template>
    <div class="e-form">
        <BillTop :title="$route.meta.title" @cancel="handleClose"></BillTop>
        <div class="tabs warningTabs"></div>
        <div class="tabs" v-if="Object.keys(formData).length != 0">
            <el-tabs tab-position="left" v-model="tabsName" @tab-click="onChangeTab">
                <el-tab-pane
                    label="基本信息"
                    name="baseInfo"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="公示内容"
                    name="publicContent"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="中标候选人"
                    name="bidWinMan"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane label="投诉受理" name="accept" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="附件信息" name="attach" :disabled="clickTabFlag"></el-tab-pane>
                <div>
                    <div id="baseInfoCon" class="con">
                        <div class="tabs-title" id="baseInfo">基本信息</div>
                        <div style="width: 100%" class="form">
                            <el-form
                                :model="formData"
                                label-width="170px"
                                :rules="rules"
                                ref="ruleForm"
                            >
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="招标编号：">
                                            <div style="display: flex">
                                                <el-input
                                                    v-model="formData.tenderApplyNo"
                                                    disabled
                                                ></el-input>
                                                <ComShowBiddingButton
                                                    :tenderId="tenderId"
                                                    mod="machine"
                                                />
                                            </div>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="招标机构">
                                            <span>{{ formData.tenderOrgName }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="拟招标项目名称：">
                                            <span>{{ formData.projectName }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="录入日期">
                                            <span>{{ formData.gmtCreate }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="招标方式：" v-if="formData.tenderForm">
                                            <span>{{
                                                formData.tenderForm | tenderForm(this)
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="招标类型：">
                                            <span>{{
                                                formData.tenderClass | tenderClass(this)
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="公示开始日期：">
                                            <el-date-picker
                                                v-model="formData.startTime"
                                                type="date"
                                                placeholder="选择日期"
                                                :clearable="false"
                                                @change="dateChange('startTime')"
                                            >
                                            </el-date-picker>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="公示结束日期：">
                                            <el-date-picker
                                                v-model="formData.endTime"
                                                type="date"
                                                placeholder="选择日期"
                                                :clearable="false"
                                                @change="dateChange('endTime')"
                                            >
                                            </el-date-picker>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="状态：">
                                            <span>{{ formData.state | state(this) }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="录入机构：">
                                            <span>{{ formData.orgName }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-form-item label="备注">
                                        <el-input
                                            type="textarea"
                                            :rows="2"
                                            placeholder="请输入内容"
                                            v-model="formData.remarks"
                                            style="margin-right: 110px"
                                        >
                                        </el-input>
                                    </el-form-item>
                                </el-row>
                            </el-form>
                        </div>
                    </div>

                    <div id="publicContentCon" class="con">
                        <div class="tabs-title" id="publicContent">公示内容</div>
                        <ComQuillEditor
                            ref="ComQuillEditor"
                            v-model="content.content"
                            :disabled="formData.releaseState === 1"
                        />
                    </div>

                    <div id="bidWinManCon" class="con">
                        <div class="tabs-title" id="bidWinMan">中标候选人</div>
                        <el-table
                            :data="bidWinTableData"
                            border
                            :cell-class-name="cellClsNm"
                            @cell-mouse-enter="cellMouseEnter"
                            @cell-mouse-leave="cellMouseLeave"
                            :max-height="$store.state.tableHeight"
            ref="table"
            v-sortTable="{ tableData: tableData, _this: this, ref: 'table' }"
                        >
                            <el-table-column
                                show-overflow-tooltip
                                prop="packageNo"
                                label="包件编号"
                                width="220"
                                class-name="blue-column"
                            >
                            </el-table-column>
                            <el-table-column
                                show-overflow-tooltip
                                prop="packageName"
                                label="包件名称"
                                width="200"
                            >
                            </el-table-column>
                            <el-table-column
                                show-overflow-tooltip
                                prop="threeCandidate"
                                label="中标单位"
                                width="230"
                            >
                            </el-table-column>
                            <el-table-column
                                show-overflow-tooltip
                                prop="firstCandidate"
                                label="第一候选人"
                                width="150"
                            >
                            </el-table-column>
                            <el-table-column
                                show-overflow-tooltip
                                prop="twoCandidate"
                                label="第二候选人"
                                width="110"
                            >
                            </el-table-column>
                        </el-table>
                    </div>

                    <div id="acceptCon" class="con">
                        <div class="tabs-title" id="accept">投诉受理</div>
                        <div class="top">
                            <div class="left">
                                <div style="margin-bottom: 20px">
                                    <el-button
                                        size="small"
                                        class="btn-greenYellow"
                                        @click="acceptAdd"
                                        >新增</el-button
                                    >
                                    <!-- <el-button size="small" class="btn-delete" @click="acceptDelete"
                                        >删除</el-button
                                    > -->
                                </div>
                            </div>
                        </div>
                        <el-table
                            :data="accepTableData"
                            border
                            style="width: 100%"
                            :cell-class-name="cellClsNm"
                            @cell-mouse-enter="cellMouseEnter"
                            @cell-mouse-leave="cellMouseLeave"
                            :max-height="$store.state.tableHeight"
            ref="table"
            v-sortTable="{ tableData: tableData, _this: this, ref: 'table' }"
                        >
                            <!--  -->
                            <el-table-column width="120" label="操作">
                                <template slot-scope="scope">
                                    <div>
                                        <i
                                            slot="reference"
                                            class="el-icon-delete"
                                            style="cursor: pointer; font-size: 20px"
                                            :class="{
                                                'icon-delete-active-color':
                                                    MouseEnterId == scope.row.dtlId
                                            }"
                                            @click="deleteAccepTableData(scope.$index)"
                                        ></i>
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column prop="contactDepart" label="联系部门" width="200">
                                <!-- slot-scope="{ row }" v-if="row.addData === 1" -->
                                <template slot-scope="{ row }">
                                    <div>
                                        <el-input
                                            v-model="row.contactDepart"
                                            placeholder="请输入内容"
                                        ></el-input>
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column prop="telephone" label="联系电话" width="150">
                                <template slot-scope="{ row }">
                                    <div>
                                        <el-input
                                            v-model="row.telephone"
                                            placeholder="请输入内容"
                                        ></el-input>
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column prop="remarks" label="备注" min-width="200">
                                <template slot-scope="{ row }">
                                    <div>
                                        <el-input
                                            v-model="row.remarks"
                                            placeholder="请输入内容"
                                        ></el-input>
                                    </div>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>

                    <div id="attachCon" class="con">
                        <div class="tabs-title" id="attach">附件信息</div>
                        <ComAttachIndex
                            bucketName="tender"
                            :relationId="billId"
                            ref="ComAttachIndex"
                            :key="1"
                        />
                    </div>
                </div>
            </el-tabs>
        </div>
        <div class="buttons">
            <el-button type="primary" class="btn-blue" @click="submit" size="small">保存</el-button>
            <el-button
                type="primary"
                slot="reference"
                class="btn-delete"
                @click="deleteData"
                size="small"
                v-if="formData.releaseState !== 1"
                >删除</el-button
            >
            <el-button
                type="primary"
                class="btn-blue"
                size="small"
                @click="release"
                v-if="formData.releaseState !== 1"
                >发布</el-button
            >
            <el-button @click="handleClose" size="small">关闭</el-button>
        </div>
        <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
    </div>
</template>

<script>
import '@/utils/jquery.scrollTo.min'
// import ComTreeTable from '@/templates/table/treeTable.vue'
// import ComTreeFile from '@/templates/table/treeFile.vue'
// import ComPagination from '@/components/pagination/pagination.vue'
import ComQuillEditor from '@/components/quillEditor.vue'
import ComAttachIndex from '@/components/common/attachIndex'
import ComShowBiddingButton from '@/pages/bidding/common/showBiddingButton.vue'
// import publicityRequest from '@/api/tender/publicity.js'
import materialMachineIncomeRequest from '@/api/tender/materialMachineIncome.js'
import { mapState } from 'vuex'

export default {
    data () {
        return {
            tabsName: 'baseInfo',
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            form: {
                name: '',
                region: '',
                date1: '',
                date2: '',
                delivery: false,
                type: [],
                resource: '',
                desc: ''
            },
            tableData: [],
            value: '',
            textarea: '',
            formData: {},
            test: '',
            selectData: [],
            selectTableColumnAttr: [
                {
                    label: '单据编号',
                    prop: 'billNo'
                },
                {
                    label: '拟招标项目名称',
                    prop: 'tenderName'
                },
                {
                    label: '单据日期',
                    prop: 'gmtCreate'
                },
                {
                    label: '单据机构名称',
                    prop: 'orgName'
                }
            ],
            selectTableColumnWidth: {
                leftWidth: '150',
                rightWidth: '100'
            },
            selectDataPagination: {},
            content: {
                content: '',
                recordId: ''
            },
            bidWinTableData: [],
            accepTableData: [],
            delAccepTableData: [],
            cloneAccepTableData: [],
            rules: {
                startTime: {
                    required: true,
                    message: '请选择公示开始日期',
                    trigger: 'change'
                },
                endTime: {
                    required: true,
                    message: '请选择公示结束日期',
                    trigger: 'change'
                }
            }
        }
    },
    computed: {
        ...mapState({
            options: state => state.biddingApplication.dictionaries
        }),
        tenderId () {
            return this.formData.tenderApplyId
        },
        billId () {
            return this.$route.query.billId || this.$route.query.billid
        },
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        }
    },
    components: {
        // ComTreeTable,
        // ComTreeFile,
        // ComPagination,
        ComQuillEditor,
        ComAttachIndex,
        ComShowBiddingButton
    },
    created () {
        // 获取基础信息
        this.getData()
        // 获取公示内容
        this.contentFindById()
        // 获取中标候选人
        this.publicityCandidateListById()
        // 投诉受理
        this.publicityComplaintListById()
    },
    mounted () {
        // 保存所有tabName
        const arr = ['baseInfo', 'publicContent', 'acceptCon', 'bidWinManCon', 'attach']
        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight(arr)
        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    const itemTop = document.getElementById(item)?.offsetTop
                    return itemTop
                })
            }
            const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if (scrollTop + 1 >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        })

        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item)?.offsetTop
                return itemTop
            })
        })
    },
    beforeDestroy () {
        this.$notify.closeAll()
    },
    methods: {
        release () {
            if (this.content.content === '') {
                this.clientPop('err', '必须填写公式内容才能发布')
                return
            }
            this.contentCreate()
            const callback = () => {
                var params = { billId: this.billId, type: '3' }
                materialMachineIncomeRequest.release(params).then(() => {
                    this.clientPop('suc', '发布成功')
                    this.getData()
                })
            }
            this.clientPop(
                'info',
                '该公示内容会发布到四川路桥官网，且无法撤回，请确认内容是否正确，谨慎操作！',
                callback
            )
        },
        publicityComplaintListById () {
            materialMachineIncomeRequest
                .publicityComplaintListById({ publicityBaseId: this.billId })
                .then(res => {
                    this.accepTableData = res
                    this.accepTableData.forEach(item => {
                        item.changeType = 0
                    })
                    this.cloneAccepTableData = JSON.parse(JSON.stringify(this.accepTableData))
                })
        },
        deleteAccepTableData (index) {
            if (this.accepTableData[index].changeType !== 1) {
                this.accepTableData[index].changeType = -1
                this.delAccepTableData.push(this.accepTableData[index])
            }
            this.accepTableData.splice(index, 1)
        },
        acceptAdd () {
            this.accepTableData.push({
                billId: this.billId,
                changeType: 1,
                contactDepart: '',
                recordId: '',
                remarks: '',
                telephone: ''
            })
        },
        publicityCandidateListById () {
            materialMachineIncomeRequest
                .publicityCandidateListById({
                    publicityBaseId: this.billId
                })
                .then(res => {
                    this.bidWinTableData = res
                })
        },
        deleteData () {
            this.clientPop('info', '确定要删除吗？数据删除后不可恢复，请谨慎操作！', this.delData)
        },
        onChangeTab (e) {
            const height = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight (arr) {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById(arr[length - 1] + 'Con')) {
                    const lastConHeight = document.getElementById(
                        arr[length - 1] + 'Con'
                    )?.offsetHeight
                    this.lastConHeight = lastConHeight
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        delData () {
            materialMachineIncomeRequest.publicityBaseDelete({ id: this.billId }).then(() => {
                const callBack = () => {
                    this.$router.push({
                        path: './machineBiddingApplicationEdit',
                        query: {
                            billid: this.tenderId,
                            seat: 'biddingPublicity'
                        }
                    })
                }
                this.clientPop('suc', '删除成功', callBack)
            })
        },
        getData () {
            materialMachineIncomeRequest.publicityBaseGetById({ id: this.billId }).then(res => {
                this.formData = res
            })
        },
        showBidding () {
            if (!this.tenderId) return // 前期需求可切换，现在不需要
            this.$notify.closeAll()
            this.$notify({
                title: '查看招标详情',
                dangerouslyUseHTMLString: true,
                message: `正式环境：客户端打开新页面<br>
                测试环境：手动打开新页面<br>
                <textarea cols="35" rows="10">http://localhost:8080/biddingApplicationShow?tenderId=${this.tenderId}</textarea>
                `,
                duration: 0
            })
            // this.$router.push({
            //     path: './biddingApplicationShow',
            //     query: { tenderId: this.tenderId }
            // })
        },
        submit () {
            // 基础信息验证
            this.$refs.ruleForm.validate(async valid => {
                if (!valid) {
                    this.onChangeTab({ name: 'baseInfo' })
                    return false
                }
            })
            // // 附件验证
            // if (this.$refs.ComAttachIndex.attachTableData.length === 0) {
            //     this.onChangeTab({ name: 'attachCon' })
            //     this.clientPop('err', '请上传附件')
            //     return false
            // }
            // 公示内容验证
            if (this.content.content === '') {
                this.onChangeTab({ name: 'publicContentCon' })
                this.clientPop('err', '请填写公示内容')
                return false
            }
            // 基础信息
            const promise1 = materialMachineIncomeRequest.publicityBaseUpdate(this.formData)
            // 公示内容
            const promise2 = this.contentCreate()
            // 投诉受理
            const promise3 = this.complainCreate()
            Promise.all([promise1, promise2, promise3]).then(() => {
                this.clientPop('suc', '保存成功')
                this.getData()
            })
        },
        async complainCreate () {
            this.ifEdit(this.accepTableData, this.cloneAccepTableData)
            const accepTableData = [...this.accepTableData, ...this.delAccepTableData]
            console.log('accepTableData', accepTableData)
            await materialMachineIncomeRequest.publicityComplaintCreate(accepTableData)
        },
        contentFindById () {
            materialMachineIncomeRequest
                .getPublicityContentById({ billId: this.billId })
                .then(res => {
                    this.content = res?.recordId
                        ? res
                        : {
                            billId: this.billId,
                            content: '',
                            recordId: ''
                        }
                    // this.cloneContent = JSON.parse(JSON.stringify(this.content))
                })
        },
        ifEdit (newData, oldData) {
            newData.forEach(item => {
                oldData.forEach(item2 => {
                    if (item.recordId === item2.recordId) {
                        if (JSON.stringify(item) !== JSON.stringify(item2)) {
                            item.changeType = 2
                        }
                    }
                })
            })
            newData
            console.log('oldData', oldData)
        },
        contentCreate () {
            materialMachineIncomeRequest
                .publicityContentCreate({
                    billId: this.billId,
                    content: this.content.content,
                    recordId: this.content.recordId
                })
                .then(() => {
                    // 刷新澄清获取接口，防止重复创建
                    this.contentFindById()
                })
        },
        getNowDate () {
            // 个位数前补0
            const zeroFill = function (num) {
                if (parseInt(num) < 10) {
                    num = '0' + num
                }
                return num
            }
            let nowtime = new Date()
            nowtime =
                zeroFill(nowtime.getFullYear()) +
                '-' +
                zeroFill(nowtime.getMonth() + 1) +
                '-' +
                zeroFill(nowtime.getDate())
            this.$set(this.formData, 'applyTime', nowtime)
        },
        handleClose () {
            this.$router.push({
                path: './machineBiddingApplicationEdit',
                query: { billid: this.tenderId, seat: 'biddingPublicity' }
            })
        },
        cellClsNm ({ column }) {
            if (column.label === '') {
                return 'fixed-left'
            }
        },
        cellMouseEnter (row) {
            this.MouseEnterId = row.id
        },
        cellMouseLeave () {
            this.MouseEnterId = 0
        }
    }
}
</script>

<style lang="scss" scoped>
.form {
    margin-top: 10px;
}

.e-table {
    background: #fff;

    /* .top {
    .left {
      padding: 20px;
      padding-top: 0px;
    }
  } */
}

.upload {
    margin: 20px auto;
    display: flex;
    justify-content: center;
    text-align: center;
}

.upload-demo {
    display: flex;
    justify-content: center;
    align-items: center;
}
</style>
